package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;

import com.zahb.qadx.BuildConfig;
import com.zahb.qadx.MainActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.DataLogin;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.JsonUtil;

public class SplashActivity extends AppCompatActivity {

    private Handler handler = new Handler();
    private Runnable runnableToLogin = this::toLoginActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_splash);
//        ImageView bgView = findViewById(R.id.bg_view);
//        if (BuildConfig.hasSplashPic) {
//            bgView.setImageResource(R.mipmap.splash);
//        } else {
//            bgView.setImageBitmap(null);
//        }
//        Thread myThread = new Thread() {//创建子线程
//            @Override
//            public void run() {
//                try {
//                    sleep(1000);//使程序休眠一秒
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        myThread.start();//启动线程



//现有业务暂时设定启动页 优点快 没有白屏
        if (!isTaskRoot()) {// 不在栈底，结束界面
            finish();
        } else {// 在栈底，即为首次启动
            SharedPreferences sp = getSharedPreferences("AccountInfo", MODE_PRIVATE);
            String loginDataStr = sp.getString("loginData", "");
            if (!CompatHelper.isEmpty(loginDataStr)) {
                try {
                    // 有登录数据，直接去首页
                    DataLogin dataLogin = JsonUtil.getGson().fromJson(loginDataStr, DataLogin.class);
                    BaseApplication.getContext().setDataLogin(dataLogin);
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 没有登录数据，去登录页
                handler.postDelayed(runnableToLogin, BuildConfig.hasSplashPic ? 1500L : 0L);
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * 跳转到登录界面
     */
    private void toLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //防止内存泄漏
        handler.removeCallbacks(runnableToLogin);
    }

}
